package model

type CardServer interface {
	Create(openId string) error
	Get(openId string) (cardInfo CardInfo, err error)
	Update(value string, volume string, id int) (err error)
}

type cardServer struct {
}

func NewCardServer() CardServer {
	return &cardServer{}
}

func (u *cardServer) Create(openId string) (err error) {
	sql := "INSERT INTO card (open_id) VALUES (?)"
	stmt, err := Db.Prepare(sql)
	if err != nil {
		return
	}
	defer stmt.Close()

	res, err := stmt.Exec(openId)
	if err != nil {
		return
	}
	_, err = res.LastInsertId()
	if err != nil {
		return
	}

	return nil
}

func (u *cardServer) Get(openId string) (cardInfo CardInfo, err error) {
	err = Db.QueryRow("SELECT * FROM card WHERE open_id = ?", openId).Scan(&cardInfo.Id, &cardInfo.OpenId, &cardInfo.C1, &cardInfo.C2, &cardInfo.C3, &cardInfo.C4, &cardInfo.C5, &cardInfo.C6, &cardInfo.C7)
	return
}

func (u *cardServer) Update(value string, volume string, id int) (err error) {
	statement := "UPDATE card SET " + volume + " = ? WHERE id = ?"
	stmt, err := Db.Prepare(statement)
	if err != nil {
		return
	}
	defer stmt.Close()

	_, err = stmt.Exec(value, id)
	return
}
